const { error } = require("console");
var express = require("express");
var router = express.Router();
const fs = require("fs");
const path = require("path");

/* GET users listing. */
router.post("/", function (req, res, next) {
  const userid = req.body.userid || "";
  console.log("🚀 ~ req.body:", req.body);
  const password = req.body.password || "";

  try {
    let data = fs.readFileSync(
      path.resolve(__dirname, "../data/data.json"),
      "utf8"
    );
    data = JSON.parse(data);
    const response = {
      username: "",
      userid: "",
      message: "",
      success: true,
    };
    const userInfo = data.users.find((item) => item.userid === userid);
    if (userInfo) {
      response.username = userInfo.username || "";
      response.userid = userInfo.userid || "";
      if (userInfo.password === password) {
        response.message = "登录成功";
        response.success = true;
        res.send(JSON.stringify(response));
      } else {
        response.success = false;
        response.message = "密码不正确，请重新输入";
        res.send(JSON.stringify(response));
      }
    } else {
      response.success = false;
      response.message = "用户不存在，请注册";
      res.send(JSON.stringify(response));
    }
  } catch (err) {
    console.error(`Got an error trying to read the file: ${err.message}`);
    res.send("error", error);
  }
});

module.exports = router;
